﻿using System;
using System.IO;
using ProtoBuf;

namespace NetFrame.EnDecode {
    /// <summary>
    /// protobuf 序列化的帮助类
    /// </summary>
    public class SeProbuf {
        /// <summary>
        /// 编码
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message"></param>
        /// <returns></returns>
        public static byte[] Se<T>(T message) {
            if (message == null) { return null; }

            MemoryStream ms = new MemoryStream();

            try {
                Serializer.Serialize<T>(ms, message);
                byte[] result = new byte[ms.Length];
                //Buffer.BlockCopy(ms.ToArray(), 0, result, 0, result.Length);
                result = ms.ToArray();
                ms.Dispose();
                return result;
            }
            catch (Exception ex) {
                ms.Dispose();
                return null;
            }

        }

        /// <summary>
        /// 解码
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T De<T>(byte[] value) {
            if (value == null || value.Length == 0) { return default(T); }

            MemoryStream ms = new MemoryStream(value);

            T result;

            try {
                result = Serializer.Deserialize<T>(ms);
            }
            catch (Exception ex) {
                ms.Dispose();
                return default(T);
            }

            ms.Dispose();

            return result;

        }
    }
}
